﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.Configuration;
using OpenPop.Pop3;
using System.Net.Mail;
using System.Collections;
    
namespace TotalSport
{
    public partial class CreateQuote : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

            //Hashtable hs = new Hashtable();
            //hs.Add("", "");
            //hs.Remove("");
            //hs.ContainsKey("");
            //Session.Add("", hs);

            BAL.conn.connectionString = ConfigurationManager.ConnectionStrings["TotalSport"].ConnectionString;
            if (Session["UserId"] == null || Session["UserId"].ToString() == "")
            {
                Session.Abandon();
                Session.RemoveAll();
                Response.Redirect("LoginUser.aspx");
            }
            else if (Session["Location"].ToString() == "Admin")
            {
                ddllocation.Enabled = true;
            }
            else
            {
                ddllocation.SelectedValue = Convert.ToString(Session["Location"]);
                ddllocation.Enabled = false;
                ddllocation.BackColor = System.Drawing.Color.LightGray;
            }

            if (!IsPostBack)
            {
                chkVAT.Checked = true;
                chkAdvance.Checked = true;
                chkDelivaryCharge.Checked = true;
                chkUrgentD.Checked = true;
                chkChquename.Checked = true;
                chkoctroi.Checked = true;
                chkValidity.Checked = true;

                DisablesubCategory();
                DisableParticulrName();
                DisableBrandName();

                BAL.Customers.PopulateLocation(ref ddllocation);
                

                btnAddProduct.Enabled = false;
                int val = BAL.Customers.GetRefNumber();
                int val1 = val + 1;
                lblRefNo.Text = val1.ToString();
                if (Request.QueryString["refno"] != null)
                {
                    int referenceno = Convert.ToInt32(Request.QueryString["refno"]);
                    lblRefNo.Text = referenceno.ToString();
                    string[] detaills = BAL.Customers.getpernldetail(referenceno);
                    txtToName.Text = detaills[3];
                    txtCompanyName.Text = detaills[6];
                    txtCno.Text = detaills[5];
                    txtEmailID.Text = detaills[4];
                    ddlPrefix.SelectedValue = detaills[2];
                    txtdsctRateforall.Text = "0";

                    //string completePath = Server.MapPath("~/PDF/" + string.Format("Quote-{0}.pdf", lblRefNo.Text));
                    //if (System.IO.File.Exists(completePath))
                    //{
                    //    System.IO.File.Delete(completePath);

                    //}
                    geteditproduct(referenceno);
                    getquotenote(referenceno);
                }
                else
                {
                    txtAdvance.Text = "50";
                    txtdelivarywithin.Text = "30";
                    txtDeliveryChanrge.Text = "0";
                    txtdsctRateforall.Text = "0";
                    txtvalidity.Text = "30";
                    chkVAT.Checked = true;
                    chkAdvance.Checked = true;
                    chkDelivaryCharge.Checked = true;
                    chkUrgentD.Checked = true;
                    chkChquename.Checked = true;
                    chkoctroi.Checked = true;
                    chkValidity.Checked = true;
                }
                getQuote();
                BAL.Customers.PopulateTemplateName(ref ddltemplate);
                btnDone.Enabled = false;
                btnsave.Enabled = false;
                btntemplate.Enabled = false;
            }
        }

        public void getquotenote(int refid)
        {
            string[] detl = BAL.Customers.getNotes(refid);
            //string subCtgry = BAL.Customers.getSubcateryName(refid);
            chkVAT.Checked = Convert.ToBoolean(detl[2]);
            chkAdvance.Checked = Convert.ToBoolean(detl[3]);
            chkDelivaryCharge.Checked = Convert.ToBoolean(detl[4]);
            chkUrgentD.Checked = Convert.ToBoolean(detl[5]);
            chkChquename.Checked = Convert.ToBoolean(detl[6]);
            chkValidity.Checked = Convert.ToBoolean(detl[7]);
            chkoctroi.Checked = Convert.ToBoolean(detl[8]);
            txtAdvance.Text = detl[10];
            txtDeliveryChanrge.Text = detl[11];
            txtdelivarywithin.Text = detl[12];
            txtvalidity.Text = detl[13];
        }
        private void geteditproduct(int referenceno)
        {
            DataSet ds = BAL.Customers.getproductquote(referenceno);
            grdAllProducts.DataSource = ds;
            grdAllProducts.DataBind();
        }
        public void getQuote()
        {
            int referencno = Convert.ToInt32(lblRefNo.Text);
            DataSet ds = BAL.Customers.getQutes(referencno);
            rptQuot.DataSource = ds;
            rptQuot.DataBind();
        }
        public void getProduct()
        {
            string category = ddlCategory.SelectedValue;
            string subcategory = ddlsubCategory.SelectedValue;
            string particularName = ddlParticularName.SelectedValue;
            string BrandName = ddlBrandName.SelectedValue;

            DataSet ds = BAL.Customers.getProduct(category, subcategory, particularName, BrandName);
            grdAllProducts.DataSource = ds;
            grdAllProducts.DataBind();
            btnAddProduct.Enabled = true;
        }
        public void DisablesubCategory()
        {
            BAL.Customers.PopulateCategBory(ref ddlCategory);
            System.Web.UI.WebControls.ListItem lst = new System.Web.UI.WebControls.ListItem("----Select SubCategory----", "-1");
            ddlsubCategory.Items.Insert(0, lst);
            ddlsubCategory.Enabled = false;
            ddlsubCategory.SelectedIndex = -1;
        }

        public void DisableBrandName()
        {
            // BAL.Customers.populateBrandName((ref ddlBrandName);
            System.Web.UI.WebControls.ListItem lst = new System.Web.UI.WebControls.ListItem("----Select Brand Name----", "-1");
            ddlBrandName.Items.Insert(0, lst);
            ddlBrandName.Enabled = false;
            ddlBrandName.SelectedIndex = -1;
        }
        public void DisableParticulrName()
        {
            System.Web.UI.WebControls.ListItem lstPname = new System.Web.UI.WebControls.ListItem("----Select Particular's Name----", "-1");
            ddlParticularName.Items.Insert(0, lstPname);
            ddlParticularName.SelectedIndex = -1;
            ddlParticularName.Enabled = false;

        }

        protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            spncategory.Attributes.Add("display", "none");
            spncategory.InnerHtml = "";

            if (ddlCategory.SelectedIndex != 0)
            {
                ddlParticularName.Enabled = false;
                ddlsubCategory.Enabled = true;
                string category = ddlCategory.SelectedValue;
                BAL.Customers.PopulateSubCategBory(ref ddlsubCategory, category);
            }
            else
            {
                DisablesubCategory();
                DisableParticulrName();
            }


        }

        protected void ShowRemoveProduct(object sender, CommandEventArgs e)
        {
            if (e.CommandName.ToString() == "RemovePro")
            {
                // int RowIndex = Convert.ToInt32(e.CommandArgument);
                int RowIndex = 0;

                LinkButton lnkremove = (LinkButton)sender;
                RepeaterItem rptitem = (RepeaterItem)lnkremove.Parent;
                RowIndex = rptitem.ItemIndex;
                HiddenField hdd = (HiddenField)rptitem.FindControl("Bindid");

                int QuoteID = Convert.ToInt32(hdd.Value);
                BAL.Customers.Deleteproduct(QuoteID);
                getQuote();
                ModalPopupExtender2.Show();
            }
        }
        protected void ddlsubCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            // if (ddlsubCategory.SelectedIndex != 0)
            //  {
            spnSubcategory.Attributes.Add("display", "none");
            spnSubcategory.InnerHtml = "";
            ddlParticularName.Enabled = true;
            string category = ddlCategory.SelectedValue;
            string subcategory = ddlsubCategory.SelectedValue;

            BAL.Customers.populateParticularname(ref ddlParticularName, category, subcategory);
            //if (ddlsubCategory.SelectedValue == "Fitness")
            //{
            //    chkVAT.Text = "10.7% VAT will be charged extra";
            //}
            //else if (ddlsubCategory.SelectedValue == "Game")
            //{

            //    chkVAT.Text = "12.5% VAT will be charged extra";

            //}

            //else if (ddlsubCategory.SelectedValue == "RECREATIONAL")
            //{

            //    chkVAT.Text = "15.2% VAT will be charged extra";

            //}
        }
        protected void ddlParticularName_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (ddlParticularName.SelectedIndex != 0)
            //{
            spnParticularNm.Attributes.Add("display", "none");
            spnParticularNm.InnerHtml = "";
            ddlBrandName.Enabled = true;
            string category = ddlCategory.SelectedValue;
            string subcategory = ddlsubCategory.SelectedValue;
            string particularName = ddlParticularName.SelectedValue;
            BAL.Customers.populateBrandName(ref ddlBrandName, category, subcategory, particularName);
        }
        
        protected void btnAddProduct_Click(object sender, EventArgs e)
        {
            string EmaildId = txtEmailID.Text;
            string toName = txtToName.Text;
            string companyName = txtCompanyName.Text;
            int refno =Convert.ToInt32(lblRefNo.Text);
            string category = ddlCategory.SelectedValue;
            string subcategory = ddlsubCategory.SelectedValue;

            int advance = Convert.ToInt32(txtAdvance.Text);
            int dlvycharge = Convert.ToInt32(txtDeliveryChanrge.Text);
            int dlvywithin = Convert.ToInt32(txtdelivarywithin.Text);
            decimal discount = Convert.ToDecimal(txtdsctRateforall.Text);
            // string particularname = ddlParticularName.SelectedValue;
            decimal Discountrate = Convert.ToDecimal("0");

            if (grdAllProducts.Rows.Count > 0)
            {
                foreach (GridViewRow gvRow in grdAllProducts.Rows)
                {//find your checkbox
                    CheckBox chkBox = (CheckBox)gvRow.FindControl("chksSelect");
                    if (chkBox.Checked == true)
                    {
                        string brandname = gvRow.Cells[1].Text;
                        string itemcode = gvRow.Cells[2].Text;
                        //  string price = gvRow.Cells[3].Text;
                        Label lblprice = (Label)gvRow.FindControl("lblid");
                        string price = lblprice.Text;
                        string particularname = gvRow.Cells[0].Text;
                        TextBox txtbox = (TextBox)gvRow.FindControl("txtDsctRte");
                        if (txtbox.Text != "")
                        {
                            Discountrate = Convert.ToDecimal(txtbox.Text);
                        }
                        decimal DsctPrice = Convert.ToDecimal(Convert.ToInt32(price) - Convert.ToInt32(price) * (Discountrate / 100));


                        TextBox txtbx = (TextBox)gvRow.FindControl("txtfinalprice");
                        //Label lbllid = (Label)gvRow.FindControl("lblid");
                        // txtbx.Text = lbllid.Text;
                        // lbllid.Text = "hiii";

                        decimal finalpricetxt = Convert.ToDecimal(txtbx.Text);
                        string loca = ddllocation.SelectedValue;

                        int subid = Convert.ToInt32(grdAllProducts.DataKeys[gvRow.RowIndex]["SubId"]);
                        BAL.Customers.InsertQuoteDetails(refno, category, subcategory,
                            particularname, brandname, itemcode, price, DsctPrice,  
                            finalpricetxt, advance,discount, subid);
                    }
                }
            }
            getQuote();
            ModalPopupExtender2.Show();
            //foreach (GridViewRow gvRow in grdAllProducts.Rows)
            //{//find your checkbox
            //    CheckBox chkBox = (CheckBox)gvRow.FindControl("chksSelect");
            //    chkBox.Checked = false; 
            //TextBox txtbx = (TextBox)gvRow.FindControl("txtfinalprice");
            //    txtbx.Text = "";
            //    TextBox txtbox = (TextBox)gvRow.FindControl("txtDsctRte");
            //    txtbox.Text = "";
            //}
            btnDone.Enabled = true;
            btnsave.Enabled = true;
            btntemplate.Enabled = true;
        }

        protected void btnDone_Click(object sender, EventArgs e)
        {
            int useid = Convert.ToInt32(Session["UserId"]);
            int refno = Convert.ToInt32(lblRefNo.Text);
            DisablesubCategory();
            // DisableParticulrName();
            //chkAdvance.Checked = true;
            //chkChquename.Checked = true;
            //chkDelivaryCharge.Checked = true;
            //chkoctroi.Checked = true;
            //chkUrgentD.Checked = true;
            //chkValidity.Checked = true;
            //chkVAT.Checked = true;
            getQuote();
            //shift data from temp to Quotes
            int refnum = BAL.Customers.shifttemp(Convert.ToInt32(refno));
            //insert personal details
            string prefixname = ddlPrefix.SelectedValue;
            string name = txtToName.Text;
            string emailid = txtEmailID.Text;
            string contn = txtCno.Text;
            string companynm = txtCompanyName.Text;
            string loca = ddllocation.SelectedValue;

            BAL.Customers.insertpersonaldetails(prefixname, name, emailid, contn,
                companynm, loca, refno, useid);

            // insert Quote notes
            bool vat = chkVAT.Checked;
            bool advane = chkAdvance.Checked;
            bool deliverycharge = chkDelivaryCharge.Checked;
            bool UrgentDay = chkUrgentD.Checked;
            bool Chquename = chkChquename.Checked;
            bool Validity = chkValidity.Checked;
            bool octroi = chkoctroi.Checked;
            int advanceamt = Convert.ToInt32(txtAdvance.Text);
            int dlvrychargeamt = Convert.ToInt32(txtDeliveryChanrge.Text);
            int dlvrywitinamt = Convert.ToInt32(txtdelivarywithin.Text);
            int qutndaysamt = Convert.ToInt32(txtvalidity.Text);

            BAL.Customers.InsertQuotNote(vat, advane, deliverycharge, UrgentDay, 
                Chquename, Validity, octroi, refno,
                advanceamt, dlvrychargeamt, dlvrywitinamt, qutndaysamt);

            GeneratePDF();

            string Name = txtToName.Text;
            string Email = txtEmailID.Text;
            string HeaderContent = "<span style='font-size:12px;font-family:Verdana'><br>" +
                    "Dear <b>" + Name + "</b>,<br><br>Your Quotation attached with this Email " +

                   "<br><br>Reference ID : <b>" + refno + "</b></span>";
            string content = "";
            content = HeaderContent;
            string strmessage = "Hi";
            string Content = "<div style=\"margin-left:20px;\">" +
                             "<span style=\"font-size: 13px; font-family: 'CENTURY GOTHIC'\">" +
                             "<br>Dear " + ddlPrefix.SelectedValue + "<b>" + txtToName.Text + "</b>,<br><br>" +
                             "Please find the attachment for the quotation as per our discussion.<br>" +
                             "Also please find the link of the product images on the below url:<br>" +
                             "<a href=\"http://host2unlimited.in/total1/ShowQuotes.aspx?refno=" + refno + "\">Click here to view the images of the products.</a><br>" +
                             "<br><br>Best Regards,<br>TOTAL SPORT Team" +
                             "<br><a href=\"http://www.totalsportsindia.in/\">www.totalsportsindia.in/</a></span><br><br></div>";

            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("host2unlimited@yahoo.com", "Host2Unlimited");
            mail.Subject = "Quotation from Total Sports";
            FileInfo objfile = new FileInfo(Server.MapPath("~/PDF/" + lblRefNo.Text + ".html"));
            StreamReader reader = new StreamReader(objfile.FullName);
            mail.Body = Content;
            if (strmessage.Length > 1)
            {
                SmtpClient client = new SmtpClient();
                client.Credentials = new System.Net.NetworkCredential("host2unlimited@yahoo.com", "123456789");
                client.Port = 25;
                string p = HttpContext.Current.Request.UserHostAddress;
                client.Host = "smtp.mail.yahoo.com";
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                mail.Attachments.Add(new Attachment(Server.MapPath("~/pdf/Quote-" + lblRefNo.Text + ".pdf")));
                mail.To.Add(Email);
                mail.IsBodyHtml = true;
                client.Send(mail);
            }
            txtEmailID.Text = "";
            txtToName.Text = "";
            txtCompanyName.Text = "";
            int val = BAL.Customers.GetRefNumber();
            lblRefNo.Text = val.ToString();
            spnMsg.Attributes.Add("style", "Display:block");
            spnMsg.InnerHtml = "Created Successfully";
            //getQuote();
            //getProduct();
            clearall();
        }
        private void clearall()
        {
            ddlPrefix.SelectedValue = "Mr.";
            txtToName.Text = "";
            txtEmailID.Text = "";
            txtCno.Text = "";
            txtCompanyName.Text = "";
            ddlCategory.ClearSelection();
            ddlsubCategory.ClearSelection();
            ddlParticularName.ClearSelection();
            ddlBrandName.ClearSelection();


        }
        protected void btnSubmitorder_Click(object sender, EventArgs e)
        {

        }

        private void GeneratePDF()
        {
            StringBuilder strBuild = new StringBuilder();
            int referenceno = Convert.ToInt32(lblRefNo.Text);
            DataSet dsquote = BAL.Customers.getQutes(referenceno);
            string[] details = BAL.Customers.getfinalpriceforhtml(referenceno);
            if (dsquote.Tables.Count > 0)
            {
                if (dsquote.Tables[0].Rows.Count > 0)
                {
                    strBuild.Append("<html><head><title></title></head>");
                    strBuild.Append("<body><div style='border:1px solid red'>");

                    string url = "../Images/logoimg.bmp";
                    strBuild.Append("<center><font size='12px'><table style='width:600px' border='0' cellspacing='3' cellpadding='3'>");
                    //<tr><td style='text-align:center' colspan='2'>");
                    //   strBuild.Append("<img src='");
                    //  strBuild.Append(url);
                    ////  strBuild.Append("' alt='No Image Available' style='width:700px;height:100px'>");    <hr style='width: 450px; text-align: center; margin-left: 80px; margin-top: 10px' />
                    //  strBuild.Append(" </td></tr>");           <hr style='width: 450px; text-align: center; margin-left: 80px; margin-bottom: 10px' />
                    strBuild.Append("<tr><td style='text-align: left; padding-left: 00px; padding-top: 40px; color: red' colspan='2'><font size='10px'> To</font>,</td></tr> <tr><td style='text-align: left; padding-left: 00px; width: 300px;color:#1748CF'><b><font size='10px'>" + txtToName.Text + "</font></b></td><td style='text-align:right;padding-right:60px;color:#1748CF'><b> Date :" +
                        DateTime.Now.ToShortDateString() + "</b></td></tr> <tr><td style='text-align: left; padding-left: 00px;color:#1748CF' colspan='2'><font size='10px'>" + txtCompanyName.Text + "</font></td></tr> ");
                    strBuild.Append("<tr><td colspan='2' style='color:#032F4D;padding-top:20px'> Thank you for your inquiry, we wish to quote our lowest for the following items.</td></tr>");
                    strBuild.Append("<tr><td colspan='2' style='text-align: left; padding-left: 00px;margin-top:30px;color:#1748CF' >  Reference  No : " + lblRefNo.Text + " </td></tr>");
                    strBuild.Append("<tr><td style='font-weight: bold; text-align: left; color: red;padding-left:00px;font-size:20px' colspan='2'><font size='10px'>Quotation Details :</font></td></tr><tr><td  colspan='2' bgcolor='#0070BA' style='color: #F0F0F0'><table style='width: 100%; color: White; border-color: #ff0000' border='1'>");
                    strBuild.Append("<tr><td style='width: 100px; text-align: center;border: 1px solid black'>Particulars Name</td><td colspan='2' style='width:300px;text-align:center;border: 1px solid black'>Particulars </td><td style='width: 100px; text-align: center;border: 1px solid black'> MRP</td><td style='width: 100px; text-align: center;border: 1px solid black'>Spl.Price</td></tr></table></td></tr><tr><td colspan='2'  bgcolor='#D4FFFF'>");
                    strBuild.Append("<table style='width: 100%; color: black;border-color:#ff0000' border='1' >");
                    foreach (DataRow dr in dsquote.Tables[0].Rows)
                    {
                        // strBuild.Append("<tr><td style='width: 50px'> 1</td>");
                        strBuild.Append("<td style='width: 310px;border-left:1px solid black'>" + dr["ParticularName"].ToString() + "</td><td  style='width: 110px'>" + dr["BrandName"].ToString() + "</td>");
                        strBuild.Append(" <td style='width: 70px;border-right:1px solid black'> " + dr["ItemCode"].ToString() + "</td> <td style='width: 65px;border-right:1px solid black'>" + dr["Price"].ToString() + " </td>");
                        strBuild.Append("<td style='width: 60px'> " + dr["DscoutPrice"].ToString() + "</td></tr>");
                        // strBuild.Append("<tr><td width='80px'>  " + dr["Picture"].ToString() + "</td><td colspan='5'>" + dr["Description"].ToString() + "</td></tr><tr><td colspan='6'>");
                    }
                    ////     strBuild.Append("<fieldset style='width:700px;color:#054287'> <legend> Notes : </legend>");
                    strBuild.Append("</table></td></tr>");
                    strBuild.Append("<tr><td colspan='2'><table style='width: 600px; color: #054287; padding-top: 20px; padding-left: 00px'><tr><td  style='font-family: Times New Roman; font-size: 25px; color: red;padding-left:00px'><font size='12px'><u>Notes:</u></font></td></tr><tr><td><table style='width: 700px; color: #054287; padding-top: 20px; padding-left: 40px'>");
                    if (chkVAT.Checked)
                    {
                        strBuild.Append("<tr><td> -> 12.5% VAT will be charged extra </td></tr>");

                    }
                    if (chkAdvance.Checked)
                    {
                        strBuild.Append("<tr><td> -> 50% Advance with P.O. and balance on delivery </td></tr>");

                    }
                    if (chkDelivaryCharge.Checked)
                    {
                        strBuild.Append("<tr><td>  -> Delivery Charges Will be Extra. </td></tr>");

                    }
                    if (chkUrgentD.Checked)
                    {
                        strBuild.Append("<tr><td>-> Delivery within 15 days from P.O.</td></tr>");

                    }
                    if (chkChquename.Checked)
                    {
                        strBuild.Append("<tr><td> -> Cheque shall be drawn in favour of  Total Sporting And Fitness Solutions Pvt.Ltd.</td></tr>");

                    }
                    if (chkValidity.Checked)
                    {
                        strBuild.Append("<tr><td> -> Validity of Quotation is 30 Days.</td></tr>");

                    }
                    if (chkoctroi.Checked)
                    {
                        strBuild.Append("<tr><td> -> All prices quoted are Ex-Works, freight, insurance,octroi, taxes and levies will be charged extra as applicable.</td></tr>");

                    }


                    strBuild.Append("</table>");

                    strBuild.Append("</td></tr><tr> <td style='color:#032F4D' border='1'>" + "<div style='border:1px solid red'> In case of any futher queries please feel free to contact us by E-mail or Phone.Thanking you and looking forward to the opportunity to serve your esteemed Organisation.</div>" + "</td></tr></table></td></tr></table></font>");

                    strBuild.Append("</div></body>");
                    strBuild.Append("</html></center>");

                }

            }

            string filePath = Server.MapPath("~/PDF/" + lblRefNo.Text + ".html");

            FileStream fs = null;
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            using (fs = File.Create(filePath))
            {
                StreamWriter strWt = new StreamWriter(fs);
                strWt.WriteLine(strBuild.ToString());
                strWt.Close();
            }

            Document pdfDoc = new Document(PageSize.A4, 60, 60, 60, 60);
            // Section section = pdfDoc.Sections[0];
            //Section section = pdfDoc.AddSection();
            //section.PageSetup.Borders.BorderType = Spire.Doc.Documents.BorderStyle.ThinThickLargeGap;


            PdfWriter.GetInstance(pdfDoc, new FileStream(Server.MapPath("~/PDF/" + string.Format("Quote-{0}.pdf", lblRefNo.Text)), FileMode.Create));


            string contents = File.ReadAllText(Server.MapPath("~/PDF/" + lblRefNo.Text + ".html"));

            // Step 4: Parse the HTML string into a collection of elements...
            pdfDoc.Open();

            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

            List<iTextSharp.text.IElement> parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);
            var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/logoimg.bmp"));
            logo.SetAbsolutePosition(54, 988);
            logo.ScaleAbsolute(415, 65);

            pdfDoc.Add(logo);
            htmlparser.Parse(new StringReader(contents));
            
            pdfDoc.Close();
        }
        protected void rptQuot_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {

            Label lblsrn = (Label)e.Item.FindControl("lblsrno");
            lblsrn.Text = (e.Item.ItemIndex + 1).ToString();

        }

        protected void chkoctroi_CheckedChanged(object sender, EventArgs e)
        {

        }

        //protected void chksSelect_CheckedChanged(object sender, EventArgs e)
        //{
        //    //CheckBox chk = (CheckBox)sender;
        //    //// GridViewRow gr = (GridViewRow)chk.Parent.Parent;
        //    ////   lblmsg.Text = GridView1.DataKeys[gr.RowIndex].Value.ToString();

        //    //int count = grdAllProducts.Rows.Count ;
        //    //foreach (GridViewRow gvRow in grdAllProducts.Rows)
        //    //{
        //    //    CheckBox chkBox = (CheckBox)gvRow.FindControl("chksSelect");
        //    //    if (chkBox.Checked == true)
        //    //    {
        //    //        count = count + 1;
        //    //    }
        //    //    else
        //    //    {
        //    //        count = count - 1;
        //    //    }

        //    //}


        //    //if (count < grdAllProducts.Rows.Count)
        //    //{
        //    //    txtCompanyName.Text = "checked";

        //    //}
        //    //else
        //    //{
        //    //    txtCompanyName.Text = "unchecked";
        //    //}
        //}

        protected void grdAllProducts_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {

        }

        protected void grdAllProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdAllProducts.PageIndex = e.NewPageIndex;
            getProduct();
        }

        protected void btn4levelsubmit_Click(object sender, EventArgs e)
        {
            if (ddlCategory.SelectedValue == "-1")
            {
                ddlCategory.Focus();
                spncategory.Attributes.Add("style", "Display:block");
                spncategory.InnerHtml = "Please Select Category";
            }
            else if (ddlsubCategory.SelectedValue == "-1")
            {
                ddlsubCategory.Focus();
                spnSubcategory.Attributes.Add("style", "Display:block");
                spnSubcategory.InnerHtml = "Please Select SubCategory";
            }
            else if (ddlsubCategory.SelectedValue == "1")
            {
                getproductgridvew();
            }
            else if (ddlParticularName.SelectedValue == "-1")
            {
                ddlParticularName.Focus();
                spnParticularNm.Attributes.Add("style", "Display:block");
                spnParticularNm.InnerHtml = "Please Select Particular Name";
            }
            else if (ddlParticularName.SelectedValue == "1")
            {
                getproductgridvew();
            }
            else if (ddlBrandName.SelectedValue == "-1")
            {
                ddlBrandName.Focus();
                spnBrandName.Attributes.Add("style", "Display:block");
                spnBrandName.InnerHtml = "Please Select Brand Name";
            }
            else
            {
                getproductgridvew();
            }
            // ModalPopupExtender2.Show();
        }

        public void getproductgridvew()
        {
            string dsctrate = txtdsctRateforall.Text;
            getProduct();

            for (int i = 0; i <= grdAllProducts.Rows.Count - 1; i++)
            {
                TextBox box1 = (TextBox)grdAllProducts.Rows[i].Cells[5].FindControl("txtDsctRte");
                TextBox box2 = (TextBox)grdAllProducts.Rows[i].Cells[6].FindControl("txtfinalprice");
                if (dsctrate != "")
                {
                    box1.Text = dsctrate;
                }
                else
                {
                    box1.Text = "0";
                }
                Label lbllid = (Label)grdAllProducts.Rows[i].Cells[0].FindControl("lblid");
                decimal discountrate = Convert.ToDecimal(box1.Text);
                int price = Convert.ToInt32(lbllid.Text);
                decimal pricedemi = Convert.ToDecimal(discountrate / 100);
                // decimal pirceinto = price * pricedemi;
                // decimal dscontedprice = Convert.ToDecimal(Convert.ToInt32(lbllid.Text) - Convert.ToInt32(pirceinto));
                decimal dscontedprice = Convert.ToDecimal((price) - ((price) * (pricedemi)));
                box2.Text = dscontedprice.ToString();
            }
        }
        protected void btnsave_Click(object sender, EventArgs e)
        {
            int useid = Convert.ToInt32(Session["UserId"]);
            int refno = Convert.ToInt32(lblRefNo.Text);
            DisablesubCategory();
            // DisableParticulrName();
            //chkAdvance.Checked = true;
            //chkChquename.Checked = true;
            //chkDelivaryCharge.Checked = true;
            //chkoctroi.Checked = true;
            //chkUrgentD.Checked = true;
            //chkValidity.Checked = true;
            //chkVAT.Checked = true;
            getQuote();
            //shift data from temp to Quotes
            int refnum = BAL.Customers.shifttemp(Convert.ToInt32(refno));
            //insert personal details
            string prefixname = ddlPrefix.SelectedValue;
            string name = txtToName.Text;
            string emailid = txtEmailID.Text;
            string contn = txtCno.Text;
            string companynm = txtCompanyName.Text;
            string loca = ddllocation.SelectedValue;

            BAL.Customers.insertpersonaldetails(prefixname, name, emailid, contn, companynm, loca, refno, useid);

            // insert Quote notes
            bool vat = chkVAT.Checked;
            bool advane = chkAdvance.Checked;
            bool deliverycharge = chkDelivaryCharge.Checked;
            bool UrgentDay = chkUrgentD.Checked;
            bool Chquename = chkChquename.Checked;
            bool Validity = chkValidity.Checked;
            bool octroi = chkoctroi.Checked;
            int advanceamt = Convert.ToInt32(txtAdvance.Text);
            int dlvrychargeamt = Convert.ToInt32(txtDeliveryChanrge.Text);
            int dlvrywitinamt = Convert.ToInt32(txtdelivarywithin.Text);
            int qutndaysamt = Convert.ToInt32(txtvalidity.Text);

            BAL.Customers.InsertQuotNote(vat, advane, deliverycharge, UrgentDay,
                Chquename, Validity, octroi, refno,
                advanceamt, dlvrychargeamt, dlvrywitinamt, qutndaysamt);

            spnMsg.Attributes.Add("style", "Display:block");
            spnMsg.InnerHtml = "Data Saved Successfully";
        }
        protected void ddlBrandName_SelectedIndexChanged(object sender, EventArgs e)
        {
            spnBrandName.Attributes.Add("display", "none");
            spnBrandName.InnerHtml = "";
        }

        protected void btntemplate_Click(object sender, EventArgs e)
        {
            string templatename = txttemplateName.Text;
            string recipientname = txtToName.Text;
            string recipientemailid = txtEmailID.Text;
            string recipientcontn = txtCno.Text;
            string companyname = txtCompanyName.Text;
            string location = "Location";
            bool vat = chkVAT.Checked;
            bool advance = chkAdvance.Checked;
            bool deliverycharges = chkDelivaryCharge.Checked;
            bool UrgentDays = chkUrgentD.Checked;
            bool ChequeName = chkChquename.Checked;
            bool Validity = chkValidity.Checked;
            bool octroi = chkoctroi.Checked;
            string category = ddlCategory.SelectedValue;

            string Subcategory = ddlsubCategory.SelectedValue;
            string ParticularName = ddlParticularName.SelectedValue;
            string BrandName = ddlBrandName.SelectedValue;
            int discountrate = Convert.ToInt32(txtdsctRateforall.Text);

            int amount = Convert.ToInt32(txtAdvance.Text);
            int delChrg = Convert.ToInt32(txtDeliveryChanrge.Text);
            int delwithin = Convert.ToInt32(txtdelivarywithin.Text);
            int validity1 = Convert.ToInt32(txtvalidity.Text);
            int refno=Convert.ToInt32( lblRefNo.Text);

            int value = BAL.Customers.InsertTemplateDetails(templatename, 0, recipientname,
                companyname, recipientemailid, recipientcontn, location,
                vat, advance, deliverycharges, UrgentDays, ChequeName, Validity, octroi, category,
                Subcategory, ParticularName, BrandName, discountrate, amount, delChrg, delwithin, validity1,refno);

            if (value == -1)
            {
                spnMsg.Attributes.Add("style", "Display:block");
                spnMsg.InnerHtml = "Template name already exist";
                //spanMsg1.Style.Add("Display", "block");
                //spanMsg1.InnerHtml = "Template name already exist";
                txttemplateName.Focus();
            }
            else
            {
                spnMsg.Attributes.Add("style", "Display:block");
                spnMsg.InnerHtml = "Template name created Successfully";
                //spanMsg1.Style.Add("Display", "block");
                //spanMsg1.InnerHtml = "Template name created Successfully";
                txttemplateName.Text = "";
            }
        }
        protected void ddltemplate_SelectedIndexChanged(object sender, EventArgs e)
        {
            string templatename = ddltemplate.SelectedValue;
            string[] detaills = BAL.Customers.SelectTemplateDetails(templatename);


            txtToName.Text = detaills[0];
            txtCompanyName.Text = detaills[1];
            txtEmailID.Text = detaills[2];
            txtCno.Text = detaills[3];
            //txtToName.Text = detaills[4];
            chkVAT.Checked = Convert.ToBoolean(detaills[5]);
            chkAdvance.Checked = Convert.ToBoolean(detaills[6]);
            chkDelivaryCharge.Checked = Convert.ToBoolean(detaills[7]);
            chkUrgentD.Checked = Convert.ToBoolean(detaills[8]);
            chkChquename.Checked = Convert.ToBoolean(detaills[9]);
            chkValidity.Checked = Convert.ToBoolean(detaills[10]);
            chkoctroi.Checked = Convert.ToBoolean(detaills[11]);
            ddlCategory.SelectedValue = detaills[12];
            BAL.Customers.PopulateSubCategBory(ref ddlsubCategory, detaills[12]);
            ddlsubCategory.SelectedValue = detaills[13];
            BAL.Customers.populateParticularname(ref  ddlParticularName, detaills[12], detaills[13]);
            ddlParticularName.SelectedValue = detaills[14];
            BAL.Customers.populateBrandName(ref  ddlBrandName, detaills[12], detaills[13], detaills[14]);
            ddlBrandName.SelectedValue = detaills[15];
            txtdsctRateforall.Text = detaills[16];
            //getProduct();
            txtAdvance.Text = detaills[17];
            txtDeliveryChanrge.Text = detaills[18];
            txtdelivarywithin.Text = detaills[19];
            txtvalidity.Text = detaills[20];
            //lblRefNo.Text = detaills[21];

        }

        protected void grdAllProducts_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // add onclick attribute for checkbox to change row back color
                CheckBox cb = (CheckBox)e.Row.FindControl("chksSelect");
                cb.Attributes.Add("onclick", "setRowBackColor(this,'" + e.Row.RowState.ToString() + "');");
                //calcutate dsct price
                TextBox tb = (TextBox)e.Row.FindControl("txtDsctRte");
                Label lbcurr = (Label)e.Row.FindControl("lblid");
                TextBox lblfinal = (TextBox)e.Row.FindControl("txtfinalprice");
                tb.Attributes.Add("onblur", "javascript: CalculateDiscount('" + lbcurr.ClientID + "',this.value,'" + lblfinal.ClientID + "');");
            }
        }

        protected void grdAllProducts_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            int referenceno = Convert.ToInt32(Request.QueryString["refno"]);
            Response.Redirect("ShowQuotes.aspx?refno=" + referenceno);
        }




    }
}